package boltdb

import (
	"encoding/binary"

	"github.com/VolantMQ/persistence"
	"github.com/boltdb/bolt"
)

func storePacket(buck *bolt.Bucket, packet persistence.PersistedPacket) error {
	var err error
	if err = buck.Put([]byte("data"), packet.Data); err != nil {
		return err
	}

	if err = buck.Put([]byte("unAck"), []byte{boolToByte(packet.UnAck)}); err != nil {
		return err
	}

	if len(packet.ExpireAt) > 0 {
		if err = buck.Put([]byte("expireAt"), []byte(packet.ExpireAt)); err != nil {
			return err
		}
	}
	err = buck.Put([]byte("createdAt"), itob64(uint64(packet.CreatedAt)))
	if err != nil {
		return err
	}
	return nil
}

func loadPacket(buck *bolt.Bucket) (pPkt persistence.PersistedPacket, err error) {
	if data := buck.Get([]byte("data")); data != nil {
		pPkt.Data = data
	} else {
		err = persistence.ErrBrokenEntry
		return
	}

	if data := buck.Get([]byte("unAck")); data != nil {
		pPkt.UnAck = byteToBool(data[0])
	}

	if data := buck.Get([]byte("expireAt")); data != nil {
		pPkt.ExpireAt = string(data)
	}
	if data := buck.Get([]byte("createdAt")); data != nil {
		pPkt.CreatedAt = int64(binary.BigEndian.Uint64(data))
	}
	return
}
